<?php
Loader::import('pspframework.utils.reader.ConfigReaderInterface');
class PhpReader implements ConfigReaderInterface {


	protected $_path = null;

	public function __construct($path = null) {
		if (!$path) {
			$path = CONFIGS . DS;
		}
		$this->_path = $path;
	}


	public function read($key) {
		if (strpos($key, '..') !== false) {
			trigger_error(sprintf('Cannot load configuration files with ../ in them.'), E_USER_NOTICE);	
		}
		if (substr($key, -4) === '.php') {
			$key = substr($key, 0, -4);
		}		
        $paths = Loader::build('config');
		$file = false ;
		foreach($paths as $path) {
			$file1 = $path . DS . $key .'.php';		
		    if (is_file($file1)) {
                $file = $file1;	
                break; 
		    }		
		}
		if ($file===false) {
		    $file = $this->_path . $key . '.php';
		    if (!is_file($file)) {
			    if (!is_file(substr($file, 0, -4))) {
				trigger_error(sprintf('Could not load configuration files: %s or %s', $file, substr($file, 0, -4)), E_USER_NOTICE);	
			    }
		    }			
		}
		include $file;
		if (!isset($config)) {
			trigger_error(sprintf('No variable $config found in %s.php', $file), E_USER_NOTICE);	
		}
		return $config;
	}


	public function dump($filename, $data) {
		$contents = '<?php' . "\n" . '$config = ' . var_export($data, true) . ';';
		return file_put_contents($this->_path . $filename, $contents);
	}

}
